﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace CueMounter.DokanStructure
{
	class DokanMirrorFile : DokanFile
	{
		public string TargetPath { get; set; }

		public DokanMirrorFile(string targetPath)
		{
			TargetPath = targetPath;
			Name = Path.GetFileName(targetPath);
		}

		public override long Length
		{
			get {
				return new FileInfo(TargetPath).Length;
			}
			set
			{
				using(FileStream fs = File.OpenRead(TargetPath))
				{
					fs.SetLength(value);
				}
			}
		}

		public override FileAttributes Attributes
		{
			get
			{
				return new FileInfo(TargetPath).Attributes;
			}
		}

		public override DokanFileDates Dates
		{
			get
			{
				return new DokanFileDates(TargetPath);
			}
			set
			{
				File.SetCreationTime(TargetPath, value.CreateTime);
				File.SetLastAccessTime(TargetPath, value.AccessTime);
				File.SetLastWriteTime(TargetPath, value.ModifyTime);
			}
		}

		public override bool CanRead { get { return true; } }
		public override bool CanWrite { get { return true; } }

		public override long Read(long streamOffset, byte[] buffer, long bufferOffset, long length)
		{
			using(FileStream fs = File.OpenRead(TargetPath))
			{
				fs.Seek(streamOffset, SeekOrigin.Begin);
				return fs.Read(buffer, (int)bufferOffset, (int)length);
			}
		}

		public override long Write(long streamOffset, byte[] buffer, long bufferOffset, long length)
		{
			using(FileStream fs = File.OpenWrite(TargetPath))
			{
				fs.Seek(streamOffset, SeekOrigin.Begin);
				fs.Write(buffer, (int)bufferOffset, (int)length);
				return length;
			}
		}
	}
}
